import express from 'express'
import fs from 'fs'
import { promisify } from 'util'
import JSONHelper from './util/jsonHelper.js'
const app = express()
const readFile = promisify(fs.readFile)

app.use('/views', express.static('./views'))
app.use('/assets', express.static('./assets'))

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.listen(9600, () => {
  // console.log('http://localhost:9600/views/index.html')
  console.log('http://localhost:9600/views/aStar.html')
})

app.get('/getAllMapGrid', async (req, res) => {
  const json = await readFile('./data/mapGridItems.json', 'utf-8')
  const data = JSON.parse(json)
  res.send(data)
})

app.post('/saveLevelMap', async (req, res) => {
  //   console.log(req.body)
  const { mapId, mapIds, mapName, enemyBots, playerBots } = req.body
  const mapMgr = await JSONHelper.read('./data/map/levelSort.json')
  console.log(mapMgr)
  if (!mapMgr) return req.send({ code: 500 })
  const exist = mapMgr.find(item => item.id == mapId)

  if (exist) {
    // 找到了就是更新
  } else {
    // 否则是新增
    const mapInfo = {
      mapId,
      mapName
    }
    mapMgr.push(mapInfo)
    JSONHelper.write('./data/map/levelSort.json', mapMgr)
    const mapData = {
      mapIds,
      enemyBots,
      playerBots
    }
    JSONHelper.write(`./data/map/leveldatas/${mapName}.json`, mapData)
  }
  res.send({ code: 200, msg: 'ok' })
})
